<?php
namespace common\utils;

use common\JPush\Client;
use common\models\Smslog;
use common\utils\welog\WeLogging;
use Yii;
use yii\base\Exception;
use yii\helpers\Url;
use yii\helpers\VarDumper;
use yii\web\UploadedFile;
use yii\db;
use common\models\SysAttachment;
use Qcloud;


/**
 * Created by PhpStorm.
 * User: hasee
 * Date: 2016/9/26
 * Time: 9:44
 */
//const LOGIN_TYPE = 1;       //登录验证码类型
class Utils
{
    const VERIFY_TYPE_LOGIN = 1;//登录
    const VERIFY_TYPE_REGISTER = 2;//注册
    const VERIFY_TYPE_CHANGE_PASSWORD = 3;//修改密码
    const VERIFY_TYPE_BOUND_BANK = 4;//绑定银行卡
    const VERIFY_WITHDRRAW = 5;//提现
    const VERIFY_SHOP_REGISTER = 6;//店铺注册
    const VERIFY_SHOP_BOUND_BANK = 7;//店铺绑定银行卡
    const VERIFY_SHOP_WITHDRAW = 8;//店铺提现
    const VERIFY_SHOP_CHANGE_PASSWORD = 9;
    const VERIFY_TYPE_BOUND_PHONE = 10;//绑定手机号

    public static function sendVerify($mobile, $verifyCode)
    {
        //短信验证码账号和密码
//        $sms_name = '18225927775';
//        $sms_password = '7E7A9EE59AA73501ACB77A58CA56';
        $accesskey = 'SGakU8jx4htcA13u';
        $secret = 'gKkURnwbVon244EbCvJCA2JSMEkmFzrh';
        $templateId = '26394';
        $sign = '【惊喜捕手】';
        $content = $verifyCode;

//        $objecturl = ;
//        $results = file_get_contents("http://api.1cloudsp.com/api/v2/single_send?accesskey=$accesskey&secret=$secret&templateId=$templateId&mobile=$mobile&sign=$sign&content=$content");

        $url = 'http://api.1cloudsp.com/api/v2/single_send';
        $post_data['accesskey']       = $accesskey;
        $post_data['secret']  = $secret;
        $post_data['templateId']  = $templateId;
        $post_data['sign']  = $sign;
        $post_data['mobile']  = $mobile;
        $post_data['content']  = $content;
        $smslog = new Smslog();
        $smslog->mobile = $mobile;
        $smslog->type = 1;
        $smslog->created_time = YII_DATETIME;
        $smslog->smscode = $content;
        $smslog->smstxt = $content;
        $results = Utils::request_post($url,$post_data);
//        var_dump($results);die;
        $jsondecode = json_decode($results); //对JSON格式的字符串进行编码
        $array = get_object_vars($jsondecode);//转换成数组
        if(!empty($array)&&$array['code'] ==0) {
            $smslog->status = 0;//成功
            $smslog->sms_uuid = $array['smUuid'];
            $smslog -> save();
            return true;
        } else {
            $smslog->status = 1;//失败
            $smslog->remark = empty($array['msg'])?'':$array['msg'];//失败
            $smslog -> save();
            return false;
        }
    }

    public static function sendMessage($mobile, $text)
    {

        $objecturl = 'http://web.cr6868.com/asmx/smsservice.aspx?name=' . Yii::$app->params['sms_name'] . '&pwd=' . Yii::$app->params['sms_password'] . '&content=' . $text . '&mobile=' . $mobile . '&stime=&sign=&type=pt&extno=';
        $results = file_get_contents($objecturl);
        //var_dump($results);die;
        $str = explode(',', $results);
        if ($str[0] == 0) {
            return true;
        } else {
            return false;
        }
    }

    //添加图片路径
    public static function addPath($image)
    {
        $image = 'http://' . $_SERVER['HTTP_HOST'] . $image;
        return $image;
    }

    //检测验证码
    public static function checkVerify($verifyCode, $veritypeType, $checkCode, $checkType)
    {
        if (!self::checkVerifyType($veritypeType, $checkType)) {
            return false;
        }
        return $verifyCode == $checkCode;
    }

    //检测验正码类型
    public static function checkVerifyType($verifyType, $checkType)
    {
        return $verifyType == $checkType;
    }

    //检测手机号
    public static function checkMobile($mobile)
    {
        if (preg_match('/^1[23465789]{1}\d{9}$/', $mobile)) {
            return true;
        } else {
            return false;
        }
    }

    //检测字符是否为空
    public static function checkStringNull($str)
    {
        if ($str == null || $str == "") {
            return true;
        } else {
            return false;
        }
    }
    //上传单个视频
    public static function uploadVideo($file)
    {
        $poster = UploadedFile::getInstanceByName($file);
        if (in_array($poster->type, array('video/ext-mp4', 'video/mp4', 'video/avi', 'video/flv', 'video/rmvb', 'video/wmv', 'video/3gp'))) {
            $names = explode(".", $poster->name);
            $imgName = rand(1000, 9999) . md5(time()) . '.' . $names[1];
            $dirPath = '/uploads/video/' . date('Ymd', time());
            $uploadDir = $_SERVER['DOCUMENT_ROOT'] . $dirPath;
            $filePath = $uploadDir . '/' . $imgName;
            $imgPath = 'http://' . $_SERVER['HTTP_HOST'] . $dirPath . '/' . $imgName;

            self::recursionMkDir($uploadDir);
            $result = $poster->saveAs($filePath);
            if ($result) {
                return $imgPath;
            } else {
                return null;
            }
        } else {
            return 'format';
        }

    }

    /*
     *  upload img to qcloud and make a record
     * @author linb
     * @date 2019年6月8日23:50:48
     * @param UploadedFile $poster
     * @param $user_id      //用户id
     * @param $shop_id      //店铺id
     * @param $type         //上传图片类型 0:代理商上传, /1/ 1:店铺上传 /shop_img/shop_1/  2:投诉上传  3:消费者上传
     * @param $return_type  //返回数据格式, 1:详细信息 0:地址
     * @param $weappid      //小程序id
     * return imgurl
     * */
    public static function uploadoneImg(UploadedFile $poster , $user_id ,$shop_id , $type , $return_type = 0 , $weappid = 0){
            $check_arr =         array('image/jpeg', 'image/gif', 'image/jpeg', 'image/jpg', 'image/png', 'image/bmp', 'image/pjpeg', 'image/x-png', 'image/jpg/png/jpeg','video/ext-mp4', 'video/mp4', 'video/avi', 'video/flv', 'video/rmvb', 'video/wmv', 'video/3gp');
            if (in_array($poster->type, $check_arr)) {
            $names = explode(".", $poster->name);
            $ext = $poster -> getExtension();
            $basename = $poster -> getBaseName();
            $filenamereal = rand(1000, 9999) . md5(time()) ;
            $param_attachment = Yii::$app->params['attachment'];
            $param_qcloud = Yii::$app->params['qcloud'];
            if($type==0){
                $url_location = '/' . $user_id . '/';
                $parentmodel = SysAttachment::getUserBaseFolder($user_id , $type);
                if(empty($parentmodel)) return null;
                $parentid = $parentmodel -> id;
            }elseif($type==1){
                $url_location = '/shop_img' . '/shop_' . $shop_id . '/';
                $parentmodel = SysAttachment::getUserBaseFolder($shop_id , $type);
                if(empty($parentmodel)){
                    $parentmodel = self::createFilefolder($shop_id , $param_attachment['shop_dir_id'] ,$type);//3
                }
                $parentid = $parentmodel -> id;
            }elseif($type==2){
                $url_location = '/usercomplaint/';
                $parentid = $param_attachment['usercomplaint_dir_id'];//2
            }else{
                $url_location = '/' . 1 . '/';

            }
            $file_name = $url_location . $filenamereal .'.'. $ext;//包含相对路径的图片地址
            //todo 上传腾讯云 获取到腾讯云的图片链接

            $appId = $param_qcloud['appId']; //"云 API 密钥 SecretId";
            $secretId = $param_qcloud['secretId']; //"云 API 密钥 SecretId";
            $secretKey = $param_qcloud['secretKey']; //"云 API 密钥 SecretKey";
            $region = $param_qcloud['region']; //设置一个默认的存储桶地域
            $cosClient = new Qcloud\Cos\Client(
                array(
                    'region' => $region,
                    'schema' => 'https', //协议头部，默认为http
                    'credentials'=> array(
                        'appId'  => $appId ,
                        'secretId'  => $secretId ,
                        'secretKey' => $secretKey
                    )));
            $local_path = $poster ->tempName;
            try {
                $result = $cosClient->upload(
                    $bucket = $param_qcloud['bucket'], //格式：BucketName-APPID
                    $key = $file_name,//$parentmodel -> file_name_real
                    $body = fopen($local_path, 'rb')

                );
                // 请求成功
                WeLogging::logging('上传图片接口记录:',var_export($result,1));


                $uploadattachmodel = new SysAttachment();
                !empty($weappid) && $uploadattachmodel -> weappid = $weappid;
                !empty($user_id) && $uploadattachmodel -> user_id = $user_id;
                !empty($shop_id) && $uploadattachmodel -> shop_id = $shop_id;
                $uploadattachmodel -> last_name =  $basename;
                $uploadattachmodel -> file_name = $basename;
                $uploadattachmodel -> file_name_real = $filenamereal;
                $uploadattachmodel -> ext = $ext;
                $uploadattachmodel -> size = $poster ->size;
                $uploadattachmodel -> url_location = $url_location;
                $uploadattachmodel -> file_type = $poster->type;
                $uploadattachmodel -> type = 0;
                $uploadattachmodel -> parent_id = $parentid;
                $uploadattachmodel -> source = 0;
                $uploadattachmodel -> md5 = md5_file($local_path);
                $uploadattachmodel ->  addAttachment();

                if($return_type ==0 ){
                    return $param_qcloud['qcloudurl'].$file_name;

                }else{
                    $send = [
                        'state' => "SUCCESS",
                        'url' => $url_location . $filenamereal .'.'.$ext,
                        'title' => $filenamereal .'.'.$ext,
                        'original' => $basename .'.'.$ext,
                        'type' => '.'.$uploadattachmodel -> file_type,
                    ];
                    return $send;
                }
                //print_r($result);
            } catch (Qcloud\Cos\Exception\CosException $e) {
                // 请求失败
                WeLogging::logging('上传图片接口记录,上传失败,错误原因:',print_r($e->getMessage(),1));
                return null;
            }
        } else {
            return null;
        }
    }

    /*
     *  upload img to qcloud and make a record
     * @author linb
     * @date 2019年6月8日23:50:48
     * @param UploadedFile $poster
     * @param $user_id
     * return imgurl
     * */
    public static function createFilefolder($id , $parent_id ,$type){
        $qcloudconfig = Yii::$app->params['qcloud'];
        $appId = $qcloudconfig['appId']; //"云 API 密钥 SecretId";
        $secretId = $qcloudconfig['secretId']; //"云 API 密钥 SecretId";
        $secretKey = $qcloudconfig['secretKey']; //"云 API 密钥 SecretKey";
        $region = $qcloudconfig['region']; //设置一个默认的存储桶地域
        $parentmodel = SysAttachment::getUserBaseFolder($parent_id , $type);
        if(!empty($parentmodel)) {
            $url_location = $parentmodel -> url_location .$parentmodel -> file_name_real ;
        }else{
            $url_location = '/';
        }
        if($type==0){
            $file_name = $url_location . '/'.$id;
            $file_name_real = $id;
        }elseif($type==1){
            $file_name = $url_location . '/shop_'.$id;
            $file_name_real =  '/shop_'.$id;
        }else{
            $file_name = $url_location . '/'.$id;
            $file_name_real = $id;
        }

        $cosClient = new Qcloud\Cos\Client(
                array(
                    'region' => $region,
                    'schema' => 'https', //协议头部，默认为http
                    'credentials'=> array(
                        'appId'  => $appId ,
                        'secretId'  => $secretId ,
                        'secretKey' => $secretKey
                    )));
            try {
                $result = $cosClient->upload(
                    $bucket = $qcloudconfig['bucket'], //格式：BucketName-APPID
                    $key = $file_name.'/',//$parentmodel -> file_name_real
                    $body = ''

                );
                // 请求成功
                WeLogging::logging('上传图片接口记录:',print_r($result,1));

//todo 录入数据库
                $uploadattachmodel = new SysAttachment();
                $uploadattachmodel -> last_name =  $file_name_real;
                $uploadattachmodel -> file_name = $file_name_real;
                $uploadattachmodel -> file_name_real = $file_name_real;
                $uploadattachmodel -> ext = '';
                $uploadattachmodel -> size = 0;
                $uploadattachmodel -> url_location = $url_location;
                $uploadattachmodel -> file_type = 'filefolder';
                $uploadattachmodel -> type = -1;
                $uploadattachmodel -> parent_id = $parent_id;
                $uploadattachmodel -> source = 0;
                $uploadattachmodel -> md5 = '';
                if($type == 0){
                    $uploadattachmodel -> user_id = $id;
                }
                $uploadattachmodel ->  addAttachment();

                return $uploadattachmodel;
                //print_r($result);
            } catch (Qcloud\Cos\Exception\CosException $e) {
                // 请求失败
                WeLogging::logging('上传图片接口记录,上传失败,错误原因:',print_r($e->getMessage(),1));
                return null;
            }

    }
    //上传单张图片
    public static function uploadImg($file ,$return_type = 0)
    {
        $poster = UploadedFile::getInstanceByName($file);

        //todo 录入上传文件信息

        //todo 如果数据库中没有该用户的文件夹,则初始化一个文件夹(20190607 todo在用户注册的时候分配一个)
        $user_id = Yii::$app->user->identity->getId();
        return self::uploadoneImg($poster , $user_id ,0,0,$return_type,0);

    }
    //小程序上传单张图片
    public static function uploadImgWeapp( $file  , $user_id , $shop_id , $type , $return_type ,$weappid)
    {
        $poster = UploadedFile::getInstanceByName($file);

        return self::uploadoneImg($poster , $user_id ,$shop_id , $type , $return_type , $weappid);

    }


    //上传多张图片
    public static function uploadImgs($file)
    {

        $poster = UploadedFile::getInstancesByName($file);
        $user_id = Yii::$app->user->identity->getId();
        $imgPaths = array();
        foreach ($poster as $value) {
            if (in_array($value->type, array('image/gif', 'image/jpeg', 'image/jpg', 'image/png', 'image/bmp', 'image/pjpeg', 'image/x-png', 'image/jpg/png/jpeg'))) {

                $imgPaths[] = self::uploadoneImg($value , $user_id,0,0,0,0);

            }
        }
        return $imgPaths;
    }

    //上传单张消息图片
    public static function uploadMsgImg($file)
    {
        $poster = UploadedFile::getInstanceByName($file);
        if (in_array($poster->type, array('image/jpeg', 'image/gif', 'image/jpeg', 'image/jpg', 'image/png', 'image/bmp', 'image/pjpeg', 'image/x-png'))) {
            $names = explode(".", $poster->name);
            $imgName = rand(1000, 9999) . md5(time()) . '.' . $names[1];
            $dirPath = '/uploads/Message/' . date('Ymd', time());
            $uploadDir = $_SERVER['DOCUMENT_ROOT'] . $dirPath;
            $filePath = $uploadDir . '/' . $imgName;
            $imgPath = 'http://' . $_SERVER['HTTP_HOST'] . $dirPath . '/' . $imgName;

            self::recursionMkDir($uploadDir);
            $result = $poster->saveAs($filePath);
            if ($result) {
                return $imgPath;
            } else {
                return null;
            }
        } else {
            return 'image_format';
        }

    }

    //上传Base64单张图片
    public static function uploadBase64Img($file)
    {
        //匹配出图片的格式
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $file, $result)) {
            $type = $result[2];
            $imgName = rand(1000, 9999) . md5(time()) . '.' . $type;
            $dirPath = '/uploads/images/' . date('Ymd', time());
            $uploadDir = $_SERVER['DOCUMENT_ROOT'] . $dirPath;
            $filePath = $uploadDir . '/' . $imgName;
            $imgPath = 'http://' . $_SERVER['HTTP_HOST'] . $dirPath . '/' . $imgName;

            self::recursionMkDir($uploadDir);

            if (file_put_contents($filePath, base64_decode(str_replace($result[1], '', $file)))) {
                return $imgPath;
            } else {
                return null;
            }
        }

    }

    //生成文件夹
    public static function recursionMkDir($dir)
    {
        if (!is_dir($dir)) {
            self::recursionMkDir(dirname($dir));
            mkdir($dir, 0777);
        }
    }

    /**
     *  Token 加密
     * @param $str
     * @return string
     */
    public static function md5Encipher($str)
    {
        return md5(md5($str . '_wife_' . time()));
    }


    /**
     * 除去数组中的空值和签名参数
     * @param array $para 签名参数组
     * return array 去掉空值与签名参数后的新签名参数组
     */
    public static function paraFilter($para)
    {
        $para_filter = [];
        foreach ($para as $key => $val) {
            if ($key == "sign" || $key == "sign_type" || $val == "") continue;
            else    $para_filter[$key] = $para[$key];
        }
        return $para_filter;
    }

    /**
     * 对数组排序
     * @param array $para 排序前的数组
     * return 排序后的数组
     */
    public static function argSort($para)
    {
        ksort($para);
        reset($para);
        return $para;
    }

    /**
     * 拼接
     * @param array $para
     * @return string
     */
    public static function createLinkstringUrlencode2($para)
    {
        $arg = "";
        foreach ($para as $key => $val) {
            $arg .= $key . '="' . ($val) . '"&';
        }
        //去掉最后一个&字符
        $arg = substr($arg, 0, count($arg) - 2);

        //如果存在转义字符，那么去掉转义
//    if(get_magic_quotes_gpc()){$arg = stripslashes($arg);}

        return $arg;
    }

    /**
     * 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
     * @param array $para 需要拼接的数组
     * return 拼接完成以后的字符串
     */
    public static function createLinkstring($para)
    {
        $arg = "";
        foreach ($para as $key => $val) {
            $arg .= $key . "=" . $val . "&";
        }
        //去掉最后一个&字符
        if(is_array($arg) || is_object($arg)){
            $length = count($arg);
        }else{
            $length = 1;
        }
        $arg = substr($arg, 0, $length - 2);

        //如果存在转义字符，那么去掉转义
        if (get_magic_quotes_gpc()) {
            $arg = stripslashes($arg);
        }
        return $arg;
    }

    /**
     * 远程获取数据，POST模式
     * 注意：
     * 1.使用Crul需要修改服务器中php.ini文件的设置，找到php_curl.dll去掉前面的";"就行了
     * 2.文件夹中cacert.pem是SSL证书请保证其路径有效，目前默认路径是：getcwd().'\\cacert.pem'
     * @param string $url 指定URL完整路径地址
     * @param string $cacert_url 指定当前工作目录绝对路径
     * @param $para 请求的数据
     * @param $input_charset 编码格式。默认值：空值
     * return 远程输出的数据
     */
    public static function getHttpResponsePOST($url, $cacert_url, $para, $input_charset = '')
    {

        if (trim($input_charset) != '') {
            $url = $url . "_input_charset=" . $input_charset;
        }
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);//SSL证书认证
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);//严格认证
        curl_setopt($curl, CURLOPT_CAINFO, $cacert_url);//证书地址
        curl_setopt($curl, CURLOPT_HEADER, 0); // 过滤HTTP头
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);// 显示输出结果
        curl_setopt($curl, CURLOPT_POST, true); // post传输数据
        curl_setopt($curl, CURLOPT_POSTFIELDS, $para);// post传输数据
        $responseText = curl_exec($curl);
        //var_dump( curl_error($curl) );//如果执行curl过程中出现异常，可打开此开关，以便查看异常内容
        curl_close($curl);

        return $responseText;
    }

    /**
     * 远程获取数据，GET模式
     * 注意：
     * 1.使用Crul需要修改服务器中php.ini文件的设置，找到php_curl.dll去掉前面的";"就行了
     * 2.文件夹中cacert.pem是SSL证书请保证其路径有效，目前默认路径是：getcwd().'\\cacert.pem'
     * @param string $url 指定URL完整路径地址
     * @param string $cacert_url 指定当前工作目录绝对路径
     * return 远程输出的数据
     */
    public static function getHttpResponseGET($url, $cacert_url)
    {
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_HEADER, 0); // 过滤HTTP头
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);// 显示输出结果
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);//SSL证书认证
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);//严格认证
        curl_setopt($curl, CURLOPT_CAINFO, $cacert_url);//证书地址
        $responseText = curl_exec($curl);
        //var_dump( curl_error($curl) );//如果执行curl过程中出现异常，可打开此开关，以便查看异常内容
        curl_close($curl);

        return $responseText;
    }

    //获取客户端IP地址
    public static function getRemoteIp()
    {
        return $_SERVER['REMOTE_ADDR'];
    }

    //post 发送xml格式的数据
    public static function postXml($url, $xmlData)
    {
        $header[] = "Content-type: text/xml";      //定义content-type为xml,注意是数组
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlData);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $response = curl_exec($ch);
        if (curl_errno($ch)) {
            self::dd(curl_error($ch));
        }
        curl_close($ch);
        $result = (array)simplexml_load_string($response, 'SimpleXMLElement', LIBXML_NOCDATA);
        return $result;
    }

    public static function dd($data)
    {
        echo "<pre>";
        print_r($data);
        echo "</pre>";
        die;
    }


    public static function time_to_format($time)
    {
        $h = floor($time / 3600);
        $m = floor(($time % 3600) / 60);
        $s = $time % 60;
        $h = $h > 9 ? $h : '0' . $h;
        $m = $m > 9 ? $m : '0' . $m;
        $s = $s > 9 ? $s : '0' . $s;
        return $h . ':' . $m . ':' . $s;

    }

    public static function format_excel2array($filePath = '', $sheet = 0)
    {
        if (empty($filePath) or !file_exists($filePath)) {
            die('file not exists');
        }
        $PHPReader = new PHPExcel_Reader_Excel2007();        //建立reader对象
        if (!$PHPReader->canRead($filePath)) {
            $PHPReader = new PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($filePath)) {
                echo 'no Excel';
                return;
            }
        }
        $PHPExcel = $PHPReader->load($filePath);        //建立excel对象
        $currentSheet = $PHPExcel->getSheet($sheet);        //**读取excel文件中的指定工作表*/
        $allColumn = $currentSheet->getHighestColumn();        //**取得最大的列号*/
        $allRow = $currentSheet->getHighestRow();        //**取得一共有多少行*/
        $data = array();
        for ($rowIndex = 1; $rowIndex <= $allRow; $rowIndex++) {        //循环读取每个单元格的内容。注意行从1开始，列从A开始
            for ($colIndex = 'A'; $colIndex <= $allColumn; $colIndex++) {
                $addr = $colIndex . $rowIndex;
                $cell = $currentSheet->getCell($addr)->getValue();
                if ($cell instanceof PHPExcel_RichText) { //富文本转换字符串
                    $cell = $cell->__toString();
                }
                $data[$rowIndex][$colIndex] = $cell;
            }
        }
        return $data;
    }

    //消息推送
    public static function push_user_message($alias = "", $tags = "", $title, $content, $extras = [], $days = 86400)
    {

        $app_key = 'bc2fcdbbe22d0937f4b8c9e4';
        $master_secret = 'b500b9d9b0adb3c75066940f';
        $log_path = $_SERVER['HTTP_HOST'] . '/log';
        $alias = strval($alias);
        $client = new  Client($app_key, $master_secret);

        // 简单推送示例

//    $result = $client->push()
//        ->setPlatform('all')
//        ->addAllAudience()
//        ->setNotificationAlert($message)
//        ->send();
        // 完整的推送示例,包含指定Platform,指定Alias,Tag,指定iOS,Android notification,指定Message等
        $push = $client->push();
        $push->setPlatform(array('ios', 'android'));
        if ($alias) {
            $push->addAlias($alias);
        } else {
            $push->addAllAudience();
        }
        if ($tags) {
            $push->addTag($tags);
        }
        $push->setNotificationAlert($title);
        $push->addAndroidNotification($content, $title, null, $extras);
        $push->addIosNotification($title, null, 0, null, null, $extras);
        //$push->addIosNotification($title);
        $push->setMessage($content, $title);
        $push->setOptions(100000, $days, null, true);
        $result = $push->send();
    }

    //消息推送
    public static function push_shop_message($alias = "", $tags = "", $title, $content, $days = 86400)
    {

        $app_key = 'b8e6bd821e8c4dd753e0f6eb';
        $master_secret = 'b500b9d9b0adb3c75066940f';
        $log_path = $_SERVER['HTTP_HOST'] . '/log';

        $client = new  Client($app_key, $master_secret);
        $alias = strval($alias);
        // 简单推送示例

//    $result = $client->push()
//        ->setPlatform('all')
//        ->addAllAudience()
//        ->setNotificationAlert($message)
//        ->send();
        // 完整的推送示例,包含指定Platform,指定Alias,Tag,指定iOS,Android notification,指定Message等
        try {
            $push = $client->push();
            $push->setPlatform(array('ios', 'android'));
            if ($alias) {
                $push->addAlias($alias);
            } else {
                $push->addAllAudience();
            }
            if ($tags) {
                $push->addTag($tags);
            }
            $push->setNotificationAlert($title);
            $push->addAndroidNotification($content, $title);
            $push->addIosNotification($title, '', 0);
            //$push->addIosNotification($title);
            $push->setMessage($content, $title);
            $push->setOptions(100000, $days, null, true);
            $result = $push->send();
        } catch (Exception $e) {

        }
    }

    //环信注册
    public static function hxreg($username, $password)
    {
        if ($username != '' and $password != '') {
            $hx = new HxClass(Yii::$app->params['Hxconfig']);
            $res = $hx->createUser($username, $password);
            $uid = $res['entities'][0]['uuid'];

            if ($uid) {
                $hx->editNickname($username, $username);
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }


    }

//下载文件
    public static function downfile($fileurl)
    {
        ob_start();
        $filename = $fileurl;
        $date = date("Ymd-H:i:m");
        header("Content-type:  application/octet-stream ");
        header("Accept-Ranges:  bytes ");
        header("Content-Disposition:  attachment;  filename= {$date}.mp3");
        $size = readfile($filename);
        header("Accept-Length: " . $size);
    }

    /**
     * 保存文件到本地
     * @param 文件路径 $url
     * @param 保存本地路径 $savePath
     * @return string
     */
    public static function downloadFile($url)
    {

        $fileName = substr($url, strrpos($url, '/') + 1);

        // $fileSize = @filesize($url);
        header('Content-Description: File Transfer');
        header('Content-Type: audio/mpeg');
        header('Content-Disposition: attachment; filename=' . basename($url));//获取带有文件扩展名的文件名
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: ' . @filesize($url));//获取文件大小
        //  var_dump(@readfile($url));die ;//输出文件
        $file = file_get_contents($url);
        $fileName = rand(0, 9999) . time() . '.mp3';
        $dirPath = '/uploads/Message/audio/' . date('Ymd', time());
        $uploadDir = $_SERVER['DOCUMENT_ROOT'] . $dirPath;
        $filePath = $uploadDir . '/' . $fileName;
        $imgPath = $dirPath . '/' . $fileName;

        self::recursionMkDir($uploadDir);
        file_put_contents($filePath, $file);
        return $imgPath;
    }

    public static function luhn($str)
    {
        $arr_no = str_split($str);
        $last_n = $arr_no[count($arr_no) - 1];
        krsort($arr_no);
        $i = 1;
        $total = 0;
        foreach ($arr_no as $n) {
            if ($i % 2 == 0) {
                $ix = $n * 2;
                if ($ix >= 10) {
                    $nx = 1 + ($ix % 10);
                    $total += $nx;
                } else {
                    $total += $ix;
                }
            } else {
                $total += $n;
            }
            $i++;
        }
        $total -= $last_n;
        $total *= 9;
        if ($last_n == ($total % 10)) {
            return true;
        } else {
            return false;
        }
    }

    /*
  16-19 位卡号校验位采用 Luhm 校验方法计算：
    1，将未带校验位的 15 位卡号从右依次编号 1 到 15，位于奇数位号上的数字乘以 2
    2，将奇位乘积的个十位全部相加，再加上所有偶数位上的数字
    3，将加法和加上校验位能被 10 整除。
*/
    public static function luhm($s)
    {
        $n = 0;
        $length = strlen($s);


        //echo strlen($s);die;
        for ($i = $length - 1; $i >= 0; $i--) {
            if ($length == 16) {
                $index = $i;
            } else {
                $index = $i - 1;
            }
            //奇数位

            if ($index % 2 != 0) {
                $n += $s{$i};

            } else {//偶数位
                $t = $s{$i} * 2;
                if ($t > 9) {
                    $t = (int)($t / 10) + $t % 10;
                }
                $n += $t;

            }

        }

        return ($n % 10) == 0;
    }

    //生成邀请码
    public static function make_coupon_card()
    {
        $code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $rand = $code[rand(0, 25)]
            . strtoupper(dechex(date('m')))
            . date('d') . substr(time(), -5)
            . substr(microtime(), 2, 5)
            . sprintf('%02d', rand(0, 99));
        for (
            $a = md5($rand, true),
            $s = '0123456789ABCDEFGHIJKLMNOPQRSTUV',
            $d = '',
            $f = 0;
            $f < 15;
            $g = ord($a[$f]),
            $d .= $s[($g ^ ord($a[$f + 1])) - $g & 0x1F],
            $f++
        ) ;
        return $d;
    }

    /**
     * @desc 根据两点间的经纬度计算距离
     * @param float $lat 纬度值
     * @param float $lng 经度值
     */
    public static function getDistance($lat1, $lng1, $lat2, $lng2)
    {
        $earthRadius = 6367000; //approximate radius of earth in meters

        /*
        Convert these degrees to radians
        to work with the formula
        */

        $lat1 = ($lat1 * pi()) / 180;
        $lng1 = ($lng1 * pi()) / 180;

        $lat2 = ($lat2 * pi()) / 180;
        $lng2 = ($lng2 * pi()) / 180;

        /*
        Using the
        Haversine formula

        http://en.wikipedia.org/wiki/Haversine_formula

        calculate the distance
        */

        $calcLongitude = $lng2 - $lng1;
        $calcLatitude = $lat2 - $lat1;
        $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
        $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
        $calculatedDistance = $earthRadius * $stepTwo;

        return round($calculatedDistance);
    }

//公里转换
    public static function change_miles($distance)
    {
        if ($distance < 100 && $distance > 0) {
            return round($distance) . 'm';
        } else if ($distance >= 100) {
            return round($distance / 1000, 1) . 'km';
        } else {
            return 0;
        }
    }

    public static function create_erweima($content, $size = '100', $lev = 'L', $margin = '0')
    {
        $content = urlencode($content);
        $image = '<img src="http://chart.apis.google.com/chart?chs=' . $size . 'x' . $size . '&amp;cht=qr&chld=' . $lev . '|' . $margin . '&amp;chl=' . $content . '"  widht="' . $size . '" height="' . $size . '" />';
        return $image;
    }

    //遍历文件夹
    public static function my_dir($dir)
    {
        $files = array();
        if (@$handle = opendir($dir)) { //注意这里要加一个@，不然会有warning错误提示：）
            while (($file = readdir($handle)) !== false) {
                if ($file != ".." && $file != ".") { //排除根目录；
                    if (is_dir($dir . "/" . $file)) { //如果是子文件夹，就进行递归
                        $files[$file] = self::my_dir($dir . "/" . $file);
                    } else { //不然就将文件的名字存入数组；
                        $files[] = $file;
                        $file_str = explode('.', $file);
                        if (self::checkStringNull($file_str[1])) {
                            rename($dir . "/" . $file, $dir . "/" . $file_str[0] . '.jpg');
                        }
                    }

                }
            }
            closedir($handle);
            return $files;
        }
    }

    //获取用户真实IP
    public static function getIp()
    {
        if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
            $ip = getenv("HTTP_CLIENT_IP");
        else
            if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
                $ip = getenv("HTTP_X_FORWARDED_FOR");
            else
                if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
                    $ip = getenv("REMOTE_ADDR");
                else
                    if (isset ($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
                        $ip = $_SERVER['REMOTE_ADDR'];
                    else
                        $ip = "unknown";
        return ($ip);
    }

    public static function getaliname($cardnumber, $cardType)
    {

        $cardTypeMap = [
            'DC' => "储蓄卡"
//            'CC' => "信用卡",
//            'SCC' => "准贷记卡",
//            'PC' => "预付费卡"
        ];
        $bank = file_get_contents(dirname(__FILE__) . '/bank.json');
        $bank_name = json_decode($bank, true);
        return $bank_name[$cardnumber] . $cardTypeMap[$cardType];
    }

    public static function format_date($time)
    {
        $t = time() - $time;
        $f = array(
            '31536000' => '年',
            '2592000' => '个月',
            '604800' => '星期',
            '86400' => '天',
            '3600' => '小时',
            '60' => '分钟',
            '1' => '秒'
        );
        foreach ($f as $k => $v) {
            if (0 != $c = floor($t / (int)$k)) {
                return $c . $v . '前';
            }
        }
    }

    /**
     * 对二维数组进行排序
     * @param $array
     * @param $keyid 排序的键值
     * @param $order 排序方式 'asc':升序 'desc':降序
     * @param $type  键值类型 'number':数字 'string':字符串
     */
    public static function sort_array(&$array, $keyid, $order = 'asc', $type = 'number')
    {
        if (is_array($array)) {
            foreach ($array as $val) {
                $order_arr[] = $val[$keyid];
            }
            $order = ($order == 'asc') ? SORT_ASC : SORT_DESC;
            $type = ($type == 'number') ? SORT_NUMERIC : SORT_STRING;
            array_multisort($order_arr, $order, $type, $array);
        }
    }

    //获取3rd_seesion
    public static function _3rd_session($len)
    {

        $fp = @fopen('/dev/urandom', 'rb');

        $result = '';

        if ($fp !== FALSE) {

            $result .= @fread($fp, $len);

            @fclose($fp);

// convert from binary to string

            $result = base64_encode($result);

// remove none url chars

            $result = strtr($result, '+/', '-_');

            return substr($result, 0, $len);

        } else {

            //trigger_error('Can not open /dev/urandom.');

            return self::create_guid();


        }


    }
    /**
     * 模拟post进行url请求
     * @param string $url
     * @param array $post_data
     */
    public static function request_post($url = '', $post_data = array()) {
        if (empty($url) || empty($post_data)) {
            return false;
        }

        $o = "";
        foreach ( $post_data as $k => $v )
        {
            $o.= "$k=" . urlencode( $v ). "&" ;
        }
        $post_data = substr($o,0,-1);

        $postUrl = $url;
        $curlPost = $post_data;
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch);//运行curl
        curl_close($ch);

        return $data;
    }

    public static function http_post_json($url, $data_string) {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'Content-Length: ' . strlen($data_string))
        );
        ob_start();
        curl_exec($ch);
        $return_content = ob_get_contents();
        //echo $return_content."<br>";
        ob_end_clean();

        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        //  return array($return_code, $return_content);
        return  $return_content;
    }
    //除去emoji 不建议去除, 应当修改数据库编码为utf8MB4 , 连接的编码也应该一同改掉
    public static function removeEmoji($text) {
        $clean_text = "";
        // Match Emoticons
        $regexEmoticons = '/[\x{1F600}-\x{1F64F}]/u';
        $clean_text = preg_replace($regexEmoticons, '', $text);
        // Match Miscellaneous Symbols and Pictographs
        $regexSymbols = '/[\x{1F300}-\x{1F5FF}]/u';
        $clean_text = preg_replace($regexSymbols, '', $clean_text);
        // Match Transport And Map Symbols
        $regexTransport = '/[\x{1F680}-\x{1F6FF}]/u';
        $clean_text = preg_replace($regexTransport, '', $clean_text);
        // Match Miscellaneous Symbols
        $regexMisc = '/[\x{2600}-\x{26FF}]/u';
        $clean_text = preg_replace($regexMisc, '', $clean_text);
        // Match Dingbats
        $regexDingbats = '/[\x{2700}-\x{27BF}]/u';
        $clean_text = preg_replace($regexDingbats, '', $clean_text);
        return $clean_text;
    }


    /**
     * 数字转换为中文
     * @param  integer  $num  目标数字
     */
    public static function number2chinese($num)
    {
        if (is_int($num) && $num < 100) {
            $char = array('零', '一', '二', '三', '四', '五', '六', '七', '八', '九');
            $unit = array('', '十', '百', '千', '万');
            $return = '';
            if ($num < 10) {
                $return = $char[$num];
            } elseif ($num%10 == 0) {
                $firstNum = substr($num, 0, 1);
                if ($num != 10) $return .= $char[$firstNum];
                $return .= $unit[strlen($num) - 1];
            } elseif ($num < 20) {
                $return = $unit[substr($num, 0, -1)]. $char[substr($num, -1)];
            } else {
                $numData = str_split($num);
                $numLength = count($numData) - 1;
                foreach ($numData as $k => $v) {
                    if ($k == $numLength) continue;
                    $return .= $char[$v];
                    if ($v != 0) $return .= $unit[$numLength - $k];
                }
                $return .= $char[substr($num, -1)];
            }
            return $return;
        }
    }

    public static function create_guid($namespace = '') {
        static $guid = '';
        $uid = uniqid("", true);
        $data = $namespace;
        $data .= $_SERVER['REQUEST_TIME'];
        $data .= $_SERVER['HTTP_USER_AGENT'];
        $data .= $_SERVER['REMOTE_ADDR'];
        $data .= $_SERVER['REMOTE_PORT'];
        $hash = strtoupper(hash('ripemd128', $uid . $guid . md5($data)));
        $guid =
            substr($hash,  0,  16) ;
        return $guid;
    }

    public static  function saveqrcode($xmlstr,$imgDir,$filename){
        //生成图片
        //$type : 0:小程序1；1：小程序2

        //$imgDir =  'upload' . DS . 'qrcode'.$type . DS;

        //$filename="qrcode".$merchantid.".jpg";///要生成的图片名字

        if(empty($xmlstr)) {
            $xmlstr = file_get_contents('php://input');
        }

        $jpg = $xmlstr;//得到post过来的二进制原始数据
        if(empty($jpg))
        {
            return 0;
        }

        $file = fopen($imgDir.$filename,"w");//打开文件准备写入
        fwrite($file,$jpg);//写入
        fclose($file);//关闭

        $filePath = './'.$imgDir.$filename;

        //图片是否存在
        if(!file_exists($filePath))
        {
            //WeLogging::logging_warning('小程序码已存在',$merchantid);
            return 0;
        }
        return 1;
    }

    /**
     *      把秒数转换为天时分秒的格式
     *      @param Int $times 时间，单位 秒
     *      @return String
     */
    public static function secToTime($times){
        $result = [
            'day'=>'00',
            'hour'=>'00',
            'minute'=>'00',
            'second'=>'00',
        ];
        $oneday = 24*60*60;//86400
        if ($times>0) {
            $day = floor($times/(3600*24));
            $lefttimes = $times - $day * $oneday;
            $hour = floor($lefttimes/3600);
            $minute = floor(($lefttimes-3600 * $hour)/60);
            $second = floor((($lefttimes-3600 * $hour) - 60 * $minute) % 60);
            $result['day'] = $day;
            $result['hour'] = sprintf('%02s', $hour);
            $result['minute'] = sprintf('%02s', $minute);
            $result['second'] = sprintf('%02s', $second);
        }
        return $result;
    }

    /*
    * array unique_rand( int $min, int $max, int $num )
    * 生成一定数量的不重复随机数，指定的范围内整数的数量必须
    * 比要生成的随机数数量大
    * $min 和 $max: 指定随机数的范围
    * $num: 指定生成数量
    */
    public static function unique_rand($min, $max, $num) {
        $count = 0;
        $return = array();
        while ($count < $num) {
            $return[] = mt_rand($min, $max);
            $return = array_flip(array_flip($return));
            $count = count($return);
        }
        //打乱数组，重新赋予数组新的下标
        shuffle($return);
        return $return;
    }
    /*
       * array unique_rand( int $min, int $max, int $num )
       * 生成一定数量的不重复随机数，指定的范围内整数的数量必须
       * 比要生成的随机数数量大
       * $min 和 $max: 指定随机数的范围
       * $num: 指定生成数量
       */
    public static function refundDecrypt($str,$key) {
        $decrypt = base64_decode($str,true);
        $key = md5($key);
        return openssl_decrypt($decrypt , 'aes-256-ecb',$key, OPENSSL_RAW_DATA);
    }
    /*
   * array unique_rand( int $min, int $max, int $num )
   * 生成一定数量的不重复随机数，指定的范围内整数的数量必须
   * 比要生成的随机数数量大
   * $min 和 $max: 指定随机数的范围
   * $num: 指定生成数量
   */
    public static function xmlToArrays($xml){
        libxml_disable_entity_loader(true);
        return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    }

}